package com.apes.scm.masterdata.product.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.party.model.Party;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.product.model.Brand;
import com.apes.scm.masterdata.product.model.CategorySupplyRange;
import com.apes.scm.masterdata.product.model.Classify;
import com.apes.scm.masterdata.product.repository.CategorySupplyRangeRepository;
import com.apes.scm.masterdata.product.repository.ClassifyRepository;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @BelongsProject: apes-server
 * @BelongsPackage: com.apes.scm.masterdata.product.service
 * @ClassName: CategorySupplyRangeService
 * @Author: pyb
 * @CreateTime: 2020-02-13 15:43
 * @Description: 品类直供范围服务
 * @Version: 1.0
 */
@Service("categorySupplyRangeService")
public class CategorySupplyRangeService extends DomainService {

    CategorySupplyRangeRepository categorySupplyRangeRepository;
    @Autowired
    private EntityManager entityManager;

    @Autowired
    private void setCategorySupplyRangeRepository(CategorySupplyRangeRepository categorySupplyRangeRepository) {
        this.categorySupplyRangeRepository = categorySupplyRangeRepository;
    }

    public static final String YYERP = "pi.yyerp.invoke";

    private CategorySupplyRange save(SimpleRequest request) {
        CategorySupplyRange supplyRange = request.getO(CategorySupplyRange.class);
        supplyRange.setClassify(SpringManager.getBean(ClassifyRepository.class).findOne((String) request.get("classifyId")));
        CategorySupplyRange categorySupplyRange = categorySupplyRangeRepository.saveAndFlush(supplyRange);
        JSONObject data = this.formatCategorySupplyRange(categorySupplyRange, request);

        synErp("plzgfwService.insert", data);
        return categorySupplyRange;
    }

    private CategorySupplyRange update(SimpleRequest request) {
        CategorySupplyRange supplyRange = request.getO(CategorySupplyRange.class);
        supplyRange.setClassify(SpringManager.getBean(ClassifyRepository.class).findOne((String) request.get("classifyId")));
        CategorySupplyRange categorySupplyRange = categorySupplyRangeRepository.saveAndFlush(supplyRange);
        JSONObject data = this.formatCategorySupplyRange(categorySupplyRange, request);
        JSONObject erp = synErp("plzgfwService.query", data);
        JSONArray parseArray = JSONArray.parseArray(erp.get("obj").toString());
        if (parseArray == null || parseArray.size() == 0) throw new RuntimeException("ERP查无此数据，更新失败！");
        data.put("TS01", ((JSONObject) (parseArray).stream().findAny().get()).getString("TS01"));
        synErp("plzgfwService.update", data);
        return categorySupplyRange;
    }

    /**
     * 格式化数据到老框架
     * @param categorySupplyRange
     * @param request
     * @return
     */
    private JSONObject formatCategorySupplyRange(CategorySupplyRange categorySupplyRange, SimpleRequest request) {
        JSONObject data = new JSONObject();
        data.put("ID", categorySupplyRange.getId());
        data.put("PLID", categorySupplyRange.getClassify().getId());
        data.put("PLMC", categorySupplyRange.getClassify().getName());
        data.put("CZY", ((PartyRole) getPerson(request)).getName());
        if (categorySupplyRange.getDept() != null) {
            data.put("CGBMID", categorySupplyRange.getDept().getId());
            data.put("CGBMMC", categorySupplyRange.getDept().getName());
        }
        if (categorySupplyRange.getBrand() != null) {
            data.put("PPID", categorySupplyRange.getBrand().getId());
            data.put("PPMC", categorySupplyRange.getBrand().getName());
        }
        return data;
    }

    private String delete(SimpleRequest request) {
        CategorySupplyRange supplyRange = request.getO(CategorySupplyRange.class);
        supplyRange.setClassify(SpringManager.getBean(ClassifyRepository.class).findOne((String) request.get("classifyId")));
        categorySupplyRangeRepository.delete(supplyRange.getId());
        JSONObject data = this.formatCategorySupplyRange(supplyRange, request);
        synErp("plzgfwService.delete", data);
        return "删除成功";
    }

    /**
     * 同步老系统
     *
     * @param method
     * @param body
     * @return
     */
    public JSONObject synErp(String method, Object body) {
        Map data = mapper("body", body, "headers", MapUtil.mapper("method", method));
        Object result = invoke(YYERP, data);
        JSONObject resultJo = JSONObject.parseObject(result.toString());
        if (!resultJo.getBoolean("success")) throw new RuntimeException(resultJo.getString("msg"));
        return resultJo;
    }

    /**
     * 1. 根据品类和品牌一起找，有则返回，没有判断品类、品牌为空是否存在
     * @param classify
     * @param branch
     * @return
     */
    public boolean checkInRange(Classify classify, Brand branch){

        List<CategorySupplyRange> categorySupplyRangeList = new ArrayList<>();
        StringBuffer qryCategorySupplyRange = new StringBuffer();
        qryCategorySupplyRange.append("SELECT A.CLASSIFY_ID, A.DEPT_ID, A.BRAND_ID FROM MAS_CATEGORY_SUPPLY_RANGE A ");
        qryCategorySupplyRange.append(" WHERE 1 = 1 ");
        qryCategorySupplyRange.append("   AND A.CLASSIFY_ID = '").append(classify.getId()).append("'");
        if (branch != null) {
            qryCategorySupplyRange.append(" AND A.BRAND_ID = '").append(branch.getId()).append("'");
        }
        Query query = entityManager.createNativeQuery(qryCategorySupplyRange.toString());
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        categorySupplyRangeList = query.getResultList();
        if (categorySupplyRangeList.size() == 0) {
            qryCategorySupplyRange = new StringBuffer();
            qryCategorySupplyRange.append("SELECT A.CLASSIFY_ID, A.DEPT_ID, A.BRAND_ID FROM MAS_CATEGORY_SUPPLY_RANGE A ");
            qryCategorySupplyRange.append(" WHERE 1 = 1 ");
            qryCategorySupplyRange.append("   AND A.CLASSIFY_ID = '").append(classify.getId()).append("' AND A.BRAND_ID IS NULL ");
            query = entityManager.createNativeQuery(qryCategorySupplyRange.toString());
            query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
            categorySupplyRangeList = query.getResultList();
        }

//        List list = SpringManager.getBean(CategorySupplyRangeRepository.class).findAll(JpaDsl.toCriteriaByEq("classify.id", classify.getId()));
        if(categorySupplyRangeList.size() != 0){
            return true;
        }else if(classify.getParents()!=null){
            return checkInRange(classify.getParents(), branch);
        } else{
            return false;
        }
    }

    /**
     * 模糊查询品类直供范围品类
     * @param classifyId
     * @return
     */
    public List<CategorySupplyRange> findLikeCategorySupplyRange(String classifyId) {
        return categorySupplyRangeRepository.findLikeCategorySupplyRange(classifyId);
    }

}
